package ua.maxicash.util.criteria.handlers;

import java.sql.Date;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Junction;
import org.hibernate.criterion.Restrictions;
import ua.maxicash.util.Filter;
import ua.maxicash.util.criteria.RestrictionsWrapper;

public class StartTimeCriteriaHandler extends CriteriaHandler {

    private static final Logger logger = Logger.getLogger(StartTimeCriteriaHandler.class);

    private Filter filter;

    public StartTimeCriteriaHandler() {
    }

    public StartTimeCriteriaHandler(List<String> aliases) {
        super(aliases);
    }

    @Override
    public void setUp(Filter filter) {
        this.filter = filter;
    }

    @Override
    public DetachedCriteria handle(DetachedCriteria criteria, Junction junction) {

        DateFormat tf = new SimpleDateFormat("HH:mm:ss");

        if (!aliases.contains("schedule")) {
            criteria.createAlias("schedule", "schedule");
            aliases.add("schedule");
        }

        try {
            junction.add(RestrictionsWrapper.getCriterion(filter.getOp(), "schedule.startTime", new Date(tf.parse(filter.getData()).getTime())));
        } catch (ParseException e) {
            logger.error(e);
        }
        return criteria;
    }
}